package com.cysyz.service.base.impl;

import com.cysyz.mylib.utils.MD5;
import com.cysyz.service.base.RegisterService;
import com.cysyz.service.base.RegisterAble;
import com.cysyz.service.base.RegisterAbleRepertory;
import com.cysyz.service.base.exception.UserIDExistException;

import java.lang.reflect.Field;

public class RegisterServiceImpl implements RegisterService {

	private RegisterAbleRepertory registerAbleRepertory;

	@Override
	public void register(RegisterAble registerAble) throws UserIDExistException {
		if (registerAbleRepertory.isExist(registerAble)) {
			throw new UserIDExistException("the user with this id is already exist:id=" + registerAble.getId());
		} else {
			Field[] fields = registerAble.getClass().getDeclaredFields();
			for (Field field : fields) {
				trimValueIfString(registerAble, field);
			}
			registerAble.setPassword(MD5.MD5Encode(registerAble.getPassword()));
			registerAbleRepertory.save(registerAble);
		}
	}

	private void trimValueIfString(RegisterAble entity, Field field) {
		if(field.getType() == String.class) {
			if (!field.isAccessible()) {
				field.setAccessible(true);
			}
			try {
				field.set(entity, field.get(entity).toString().trim());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
}
